package com.xtaller.common.kit;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.common.bean.AuthInfo;
import com.xtaller.common.bean.JWTResult;
import com.xtaller.common.convert.J;
import io.jsonwebtoken.*;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @author Taller
 * @create 2018-04-13 17:36
 */
public class JwtKit {
    public static final int JWT_ERRCODE_EXPIRE = 4001;			//Token过期
    public static final int JWT_ERRCODE_FAIL = 4002;			//验证不通过
    public static final String JWT_SECRET = "8677df7fc3a34e26a61c034d5ec8245d";			//密匙

    /**
     * 签发JWT
     * @param id
     * @param info   认证数据
     * @param ttlMillis
     * @return  String
     */
    public static String createJWT(String id, AuthInfo info, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(J.o2s(info))                  // 主题
                .setIssuer(info.getModule())              // 签发者
                .setIssuedAt(now)                         // 签发时间
                .signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙
        if (ttlMillis > 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            builder.setExpiration(expDate); // 过期时间
        }
        return builder.compact();
    }

    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static JWTResult validateJWT(String jwtStr) {
        JWTResult jwt = new JWTResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            jwt.setSuccess(true);
            jwt.setClaims(claims);
        } catch (ExpiredJwtException e) {
            jwt.setErrCode(JWT_ERRCODE_EXPIRE);
            jwt.setSuccess(false);
        } catch (SignatureException e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
        } catch (Exception e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
        }
        return jwt;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECRET);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 读取认证信息
     * */
    public static AuthInfo readSubject(String jwt){
        Claims claims = null;
        try {
            claims = parseJWT(jwt);
            return J.s2m(claims.getSubject(), AuthInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) throws Exception {
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyMSIsInN1YiI6IntcImFwcElkXCI6XCIxMjM0NTY3ODlcIixcImFwcFNlY3JldFwiOlwiOTg4Nzg3NzdcIixcInBsYXRmb3JtXCI6Mn0iLCJpc3MiOiLnlKjovablrp0iLCJpYXQiOjE1MjE3ODIyOTZ9.MrgUu8118hklDpX1hIs_xUpcnFZuDrRpqiUdV5KkWBo");
        AuthInfo info = J.s2m(claims.getSubject(), AuthInfo.class);
        info.setId(claims.getId());
    }
}
